﻿#region License
// (c) Garry McGlennon 2009
// 
// This project is made available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warrenty – Use at your own risk
// 
// View the project and the latest code at http://dnpframework.codeplex.com/
// 
// All other rights reserved.
// 
// blog: www.dotNetProfessional.com/blog/
#endregion
using System;
using System.Collections;
using System.Web;

namespace dnp.Framework.Web
{
    /// <summary>
    /// This class allows the ability to safely store data that
    /// can be shared only with the currently active thread.
    /// In ASP.NET applications this is simulated due to the
    /// issues with thread swapping during a page execution.
    /// 
    /// Note: The data stored only lasts for the duration of the 'logical' thread
    /// </summary>
    /// <remarks>A discussion of the issue can be found at: http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html</remarks>
    public class SafeLocalStorage
    {
        /// <summary>
        /// This variable is used to record data when NOT within an
        /// ASP.NET application.
        /// </summary>
        [ThreadStatic]
        private static Hashtable _dataItems = new Hashtable();

        public static void StoreItem<T>(string key, T value)
        {
            if (HttpContext.Current != null)
                HttpContext.Current.Items.Add(key, value);
            else
                if (_dataItems.Contains(key))
                    _dataItems[key] = value;
                else
                    _dataItems.Add(key, value);
        }

        public static T RetrieveItem<T>(string key)
        {
            if (HttpContext.Current != null)
                return (T)HttpContext.Current.Items[key];
            else
                return (T)_dataItems[key];
        }
    }
}
